var exist = function (board, word) {
  let h = board.length, w = board[0].length
  // 用来记录这个数是否被使用过
  let visited = new Array(h).fill([]).map(() => Array(w).fill(false))
  // 分别是右、左、下、上操作
  const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
  const check = (i, j, index) => {
    if (board[i][j] != word[index]) return false
    if (index == word.length - 1) return true
    // 进入到下面的说明字符匹配上的
    visited[i][j] = true
    let result = false
    for (let [dx, dy] of directions) {
      let newi = i + dx
      let newj = j + dy
      if (newi < h && newi >= 0 && newj >= 0 && newj < w) {
        // 如果没有被使用过进入循环
        if (!visited[newi][newj]) {
          const flag = check(newi, newj, index + 1)
          if (flag) {
            result = true
            break
          }
        }
      }
    }
    //  每次循环出来前记得将使用过的去除掉标记
    visited[i][j] = false
    return result
  }
  for (var i = 0; i < h; i++) {
    for (var j = 0; j < w; j++) {
      const flag = check(i, j, 0)
      if (flag) return true
    }
  }
  return false
}
let board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]
let word = "ABCCED"
console.log(exist(board,word))